package com.a2.appa3.ui.activity;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.duma.ld.mylibrary.SwitchView;
import com.google.gson.Gson;
import com.nanchen.compresshelper.CompressHelper;
import com.a2.appa3.R;
import com.a2.appa3.global.HttpAdress;
import com.a2.appa3.global.Info;
import com.a2.appa3.model.network.entity.req.Resbuildground;
import com.a2.appa3.model.network.entity.req.uploadGroundBean;
import com.a2.appa3.util.BaseLoadingDialog;
import com.a2.appa3.util.SYSOUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import me.shihao.library.XStatusBarHelper;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.a2.appa3.ui.activity.ChatActivity1.fileToBase64;

public class NewgroundActivity extends BaseActivitySimple {

    @BindView(R.id.ivback)
    ImageView ivback;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.headerTitle)
    TextView headerTitle;
    @BindView(R.id.headerButton)
    ImageView headerButton;
    @BindView(R.id.headerButtonRoot)
    LinearLayout headerButtonRoot;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.group_header)
    ImageView groupHeader;
    @BindView(R.id.groupname)
    EditText groupname;
    @BindView(R.id.grouswitch)
    SwitchView grouswitch;
    @BindView(R.id.creategroundbt)
    TextView creategroundbt;
    @BindView(R.id.hideview)
    View hideview;
    private int upload = 999;
    private String picture;//bas64头像
    private String isflag = "2";//bas64头像
    Handler mainHandler = new Handler(Looper.getMainLooper());
    private BaseLoadingDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        if (Build.VERSION.SDK_INT >= 21) {
            //解决Android5.0以上，状态栏设置颜色后变灰的问题
            XStatusBarHelper.tintStatusBar(this, getResources().getColor(R.color.settingbg));
        }
        groupname.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    hideview.setVisibility(View.VISIBLE);
                } else {
                    hideview.setVisibility(View.GONE);
                }
            }
        });
        headerTitle.setText("新建群聊");
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        groupHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("android.intent.action.GET_CONTENT");
                intent.setType("image/*");
                startActivityForResult(intent, upload);//打开系统相册
            }
        });
        grouswitch.setOnClickCheckedListener(new SwitchView.onClickCheckedListener() {
            @Override
            public void onClick() {
                if (grouswitch.isChecked()) {
                    isflag = "1";
                } else {
                    isflag = "2";
                }
            }
        });
        creategroundbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(groupname.getText().toString().trim())) {
                    SYSOUtils.sOut_("图片" + picture);
                    SYSOUtils.sOut_("创建群聊图片" + "名称" + groupname.getText
                            ().toString().trim() + "状态" + isflag);
                    buildRoom(groupname.getText().toString().trim());
                    dialog = new BaseLoadingDialog(NewgroundActivity.this, R.style.custom_dialog2);
                    dialog.show();
                } else {
                    Toast.makeText(NewgroundActivity.this, "请输入群聊名称", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    Gson gson = new Gson();

    private void buildRoom(String trim) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        uploadGroundBean bean = new uploadGroundBean();

        bean.token = Info.Token;
        bean.is_auto = isflag;
        bean.roomName = trim;
        if (TextUtils.isEmpty(picture)) {
            bean.headImg = "\n" +
                    "FhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgo\n" +
                    "KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAPAAhwDASIA\n" +
                    "AhEBAxEB/8QAHQAAAgMBAQEBAQAAAAAAAAAABQYDBAcCAQAICf/EAEwQAAIBAwIEBAIHBgUCBQMA\n" +
                    "CwECAwAEEQUhBhIxQRMiUWFxgQcUMkKRobEVIyRSwdEzYnLh8CXxFjRDU2MmNYIINhdzg5KissJE\n" +
                    "0v/EABsBAAMBAQEBAQAAAAAAAAAAAAIDBAEFAAYH/8QAMxEAAgIBBAECBQQCAQUAAwAAAAECAxEE\n" +
                    "EiExIjJBBRNRYXEjM0KBFEORFVKhwdFisfD/2gAMAwEAAhEDEQA/ANL1NOa6sYOwGSKs3Sh9ZtYj\n" +
                    "uEXmNeyJ4mvgj7iACuwAdblY/dQ4/CoTq/Qox/vLnUJj3blFXIB/FMMfcUVRtD/DSns0u1EtKUz6\n" +
                    "nIe3MBivPtGNjHJ5LW2//egCrcp5bZx/8lQ3X2LVf/l2ruY/wxP/AMtNJPcji+0M95KXOKP/ALXP\n" +
                    "j/3cg/OmO2HnGepkJFLvE4P7Imx3kxWPoZH1FK6C8mj5G2VqzxuRlPgKr6gOVdI+K1Px2PMn+kUv\n" +
                    "+LHR9Uf7Jb1hz6e/+nFLX0l7XiH1GaZL7CxaYx6+UUC+kyHMsTjoRWS6Ng/Jf2D+KMGCxkx/6Yp7\n" +
                    "kcXXBaH1jBpJ4jU/sLT3/wAg/SnbQMTcExZ6eHj8q2HLkvsbd6Yv7gHRW8fhO4i/kZtqo/Rs3LrU\n" +
                    "8WdmXeifDEXNpepx9gxpe4Lka34uVAcBiwNDnEkzUsxmi/fBrTjJfQyfrVbiAG14uhlJwCVarXGo\n" +
                    "MHEsco7FT+dc8eREXVpcj7yDeswlnH1Cj/F/VBb6Q4frGkpKN8oDQ76Jp1IurUnBO4o/qsYveFYG\n" +
                    "Jz+7FI3AtwLHiNFLYDkrRPifIEVuqcRo1+A29y79jV7gvUglw1vIftdKIcU2okgLKu+KQrK7NnqU\n" +
                    "bk45W3oHmEj0V8yvBqmrwrLAdt8Vm2rwFJCT2NafBKl5YJKm4ZaVda03LkhdjRWrnIvTz2+LE6HV\n" +
                    "buw3gcgehNXX4k1C7jCGUge1fXWnEEgjPpXFrprq/TapvJdFb2vlot6ZNch/F8Rg3Y5ok9xqdypX\n" +
                    "6w2P8u1S2Gn+UUYtbApRpNipSiKtxp94g8TxJGP+Yk0Q0LTJp5Oa5JI9KZLq0LxDGxFeadGYJPMf\n" +
                    "kaYq+eRTt8Xgs21gIpQVXarciEA/CricpjyPSq85LE1VGG1cEUptgp4y4JYd67jYIQBivbyZYYzn\n" +
                    "Y1SsmM9yBkkUqXDwh0VmIWvpxBYSPnGBQrhuXxbeaQ9zUfGVz4GncgOGbauOGj4Wil29CTRt4ml9\n" +
                    "AYr9NyPbOcPqM/ep4pAY7k9dqD6HL4l1dydhneu9PnMkN4ewBpal0Ocf/RatJOfTpTscNvXuunOj\n" +
                    "o/YYNB9AuDLZ3qk7DJolqLh+GifQYrY9f0eaxIqwTeJohI7GjmnfxGjMM52NKmjS8+i3C5+yDTBw\n" +
                    "nIX0x1znrXq30bcuH+TrQ3Pnjb4VBanwdRIH81R6VNyajInvXk8gXWGX1OazPjj7mYe5/dDhKOez\n" +
                    "f4UJ0GUfvU9DRSHLWZ/00v6M/hahNG3qaol7MRFZTR7ZsYdblQ5GWo/FtcuM/aGaBX45NaRh94Cj\n" +
                    "h2mibuRWQ7ZsuUn9iS5HPasOuOlJmpQlZycU7AZRx2pZ1tOWTNbYuAauASgKXSn2zTBC5Zd96DgZ\n" +
                    "aM49s0UtTiPY0tDXyCNUh5LtiOjDNVQpR1Ydjmjepop8M4Gc4ocIuYnA2rzRqlwMlk6SRnbzEZFQ\n" +
                    "3gxgge1fWPN4MRA6DBqa4XmQ7VvsL9wfzECQdcrn8KqzSZVXPririZE67bZIqC5XMDqVwVrGH7k1\n" +
                    "s3Mi4+FXYn7HsaGadISrfI1fQgyHPcYrEC0SF/DnHxwfnVqR8R8ynzKdx7UPvgcKy9SPwNSWsgkk\n" +
                    "Gfsyrj50WccAtZLizFnMednHMtSWl4JC0bf4idRQSWVlRwpxJC3MD7V7ezCKWG+i+y43+PetUmjN\n" +
                    "oxpKsnTYjqKikDdV3oNcXPKI7y3J5T1GaJwXQurMXEPUdRRqeewHBrkFa7fzpbGPlIBGM0iyxM7l\n" +
                    "iOtaXJHBqluQSBIO1DjoABPkB+dKnCUuSmqcYrDFtRnWWPsP0qODJ1C9fsF2qe3HNqkh9KjgI/jT\n" +
                    "3GRQId/8KFtF/DW6jfml5jRrhaIy3Lv0/eE/hVW3jxDDkfZUtRbhCPlQux6qzfia8lloGcsJl29O\n" +
                    "HslB/wDUJ/OpJTm1z/8ALUF1hrixHuTXcpItYgPvSE0wR7Ilst5EP+ZqXeKWC6Ods80h/WmXT1HK\n" +
                    "p/1E0s8Vj/pUA9ZP61kuIhw9RW1M5fSl90q5xmmTGPUCq+qgC70kAbZX+lW+MDyyxdNgKX/FjY+p\n" +
                    "f2c6xCxsdPK9Ry0L+kOLNrCT15RRvWpCNNssDstDPpCx+zoGP8oxWT6Z6v1IC60vicKWL+i7U18B\n" +
                    "v4/CgRugBH60q3TCTgq1P8pxTR9Gg8Th+VR/MRRV+r+j1ufl/wBlTh4KJdVt1O25xSTYTi04qicb\n" +
                    "ATYNN+lH6vxVfQk/bQ0la7GbfXXYbYfP50qTwk/oOr5bX1Q3fSNFm5gnH3gK44mAu+FLO5UZKYBN\n" +
                    "X+L1+scPWU/UhBVK0/ieBriPr4ZNFLO6S+qAjLwj9mENAlN7wjGvVkHLWceay4iV+mHz+dPn0cyi\n" +
                    "XT7uA/d3xSfxRH4GrscAb0DeUmMrWJyibDIVvdLjkBzzIKy7iC1NtevnoTkVoPBN0t9oSpnLJ5fe\n" +
                    "hPGemBrYug843pliykxFMtktrL/0f6j49n9Wc5Kjama8tQ4OBkHpWP8AD2pPpl4rAnAO4rY9MvYt\n" +
                    "QtEljYHI3HpRVNTW1gaiDrluXQv3emEsMAGrNtpKhVJXc0wm2B9KkEYXHei+RyJ+e8YQIis1jztv\n" +
                    "VlIQOteatdx2Fq08nboKQL7ie5luueOTlXOwB2oZba3hmxhO3lGhsoxVaSOPOSwU+uaQ5+KrsRkc\n" +
                    "/wACBQK91u8lJYzOD65oXdH2Gx00/dmvxXKhSoYY+NC9U1q3tQVDB5Om1ZOmq3TSKvjye/mopBHc\n" +
                    "XjDl5sHqSax6ltYQf+HteZMPXF/NeyjfvsKZ9Cs2t7cyynBqjw5oojRHkGSNyTUXGfEEdhbNZWrh\n" +
                    "pm2Yj7tbBY85gWPL+XABcT6n+0tWS1hOVDYxTFqBGn8OlRsSoHxpa4H0l7q7+uTjvkZotxldCWeK\n" +
                    "yhOSCM1kZNpzZs44ca17FfQF8HR7iZu4O9cWpa30G7mPVs4NW9Q5bLRoLbozbmq3EBFvwxHGuxev\n" +
                    "Lj+kEuf7ZT4UUjSb126mi95/+qj59Ko6Iot+HGJ6uava+fA4UA6FgKOv0/0ZPmf9gLQGA0e7z2BN\n" +
                    "GOAZ/EgkXPrS/pb+FoF43ciiv0c5MEjUFb5iHauJHUEvJr8g7c9W9aPg6uHHUgGhbPjiVx6vRHiR\n" +
                    "sahH7qK1+/5BXcfwOGmymWzUnrilq3k5decepxij2h/+UXfNLM7cnEJx1z0psm9qEw9TQX1wMLm3\n" +
                    "kG2aL5JhhbrQniInwbdh2NE4GDaahHUYpke2LfpTL0e779xQfV7fnxjrmisJyUPtVTVm5VYjqKKf\n" +
                    "KBhwwDcQGGABs7HNXLJeaMn3qtJceOHDdcVZsGyoI6EZpKHPo6v4/wCHYgbgVQRcD2o2VDIwPQ0G\n" +
                    "AxlT2yK2SwZFhDRpCI5FPY1eZeZT70I09+W4KD7woumfDHN616PQMuyo0WDzYzg5r26iJZiB13qy\n" +
                    "VGD3riccyq3titwZlgWyPJI";
        } else {
            bean.headImg = picture;
//            SYSOUtils.sOut_("BAS64串数" + picture);
        }
        String json = gson.toJson(bean);
//        long starttime = System.currentTimeMillis();
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);
        final Request request = new Request.Builder()
                .url(HttpAdress.getuseAdress() + "api/chatapi/ChatRoom/buildRoom")//请求的url
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                dialog.dismiss();
                SYSOUtils.sOut_("上传失败，原因是" + e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Resbuildground bena1 = gson.fromJson(response.body().string(), Resbuildground.class);
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        //已在主线程中，可以更新UI
                        if (bena1.code == 0) {
                            Toast.makeText(NewgroundActivity.this, "创建成功", Toast.LENGTH_SHORT).show();
                            finish();
                            startActivity(new Intent(NewgroundActivity.this, GroundActivity.class));
                        } else {
                            Toast.makeText(NewgroundActivity.this, bena1.msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_newground;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999 && resultCode == this.RESULT_OK && null != data) {
            if (Build.VERSION.SDK_INT >= 19) {
                handleImageOnKitkat(data);
            }
        }
    }

    @TargetApi(19)
    private void handleImageOnKitkat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //如果是document类型的uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content:" +
                        "//downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content类型的uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是File类型的uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        Glide.with(NewgroundActivity.this).load(imagePath)
                .into(groupHeader);
        SYSOUtils.sOut_("++++++++++++++++++++++++++++++++++++++" + imagePath.toString());
        displayImage(imagePath);//根据图片路径显示图片
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过uri和selection来获取真实的图片路径
        Cursor cursor = this.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    //压缩图片
    public void displayImage(String path) {
        SYSOUtils.sOut_("这里是什么" + path);
//        //开始上传
        File file = new File(path);
        SYSOUtils.sOut_("压缩前相ce图片正常大小" + file.length());
        File newFile = CompressHelper.getDefault(this).compressToFile(file);
        SYSOUtils.sOut_("压缩后相ce图片正常大小" + newFile.length());
        String strbm = fileToBase64(String.valueOf(newFile));
//            //相册
        picture = "data:image/png;base64," + strbm;
    }
}
